<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Factory as Auth;
use Illuminate\Http\Request;
use Tymon\JWTAuth\JWTGuard;

class SDKAuth
{
    protected $auth;

    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    public function handle(Request $request, Closure $next)
    {
        $agentId = (int) $request->header('Agent-Id', 0);

        // 区别于 Authenticate, 这里只供于 sdk
        // 切换默认守卫, 优化控制器免手动选择
        config(['auth.defaults.guard' => 'h5']);

        /** @var JWTGuard $h5Guard */
        $h5Guard = $this->auth->guard('h5');
        (empty($agentId) || !$h5Guard->byId($agentId)) && abort(401, trans('auth.please_sign_in'));
        // 优化 控制器里获取用户信息时候避免再一次查询
        app(\Dingo\Api\Auth\Auth::class)->setUser($h5Guard->getUser());

        return $next($request);
    }
}
